package com.learn.core.controller.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LCoursewareType;
import com.learn.core.domain.LDict;
import com.learn.core.dto.LCoursewareTypeDTO;
import com.learn.core.service.ILCoursewareTypeService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-13 19:39:45
 * @describe 课件分类表前端控制器
 */
@Api("课件类型")
@RestController
@RequestMapping("/manager/ctyp")
public class LCoursewareTypeController extends WebController<LCoursewareType> {
    @Autowired
    private ILCoursewareTypeService ilCoursewareTypeService;

    //课件类型树
    @ApiOperation(value = "课件类型树")
    @UserLoginToken
    @PostMapping("/tree")
    public CommonResult<Object> tree(){
        try {
            List<LCoursewareType> lCoursewareTypes = ilCoursewareTypeService.queryLCoursewareTypeAll();
            if(lCoursewareTypes.size()>0)
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lCoursewareTypes);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LCoursewareType> list(@RequestBody LCoursewareTypeDTO lCoursewareTypeDTO){
        try {
            if(lCoursewareTypeDTO==null){
                return new PageResult<LCoursewareType>(null, null, ResultEnum.ERROR);
            }
            if(lCoursewareTypeDTO.getPage()==null||lCoursewareTypeDTO.getRows()==null){
                return new PageResult<LCoursewareType>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCoursewareTypeDTO.getPage(),lCoursewareTypeDTO.getRows());
            QueryWrapper<LCoursewareType> queryWrapper = new QueryWrapper<>();
            if(lCoursewareTypeDTO.getCoursewareTypeId()!=null)
                queryWrapper.eq("parent_node",lCoursewareTypeDTO.getCoursewareTypeId());
            else {
                queryWrapper.eq("parent_node",0);
            }
            Page<LCoursewareType> lCoursewareTypes = (Page<LCoursewareType>) ilCoursewareTypeService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCoursewareTypes)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCoursewareTypes.getTotal(), lCoursewareTypes, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加课件分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LCoursewareType lCoursewareType, HttpServletRequest request){

        try {
            if(lCoursewareType!=null) {
                if (StringUtils.isEmpty(lCoursewareType.getCoursewareTypeName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSEWARE_NAME);
                }
                if (StringUtils.isEmpty(lCoursewareType.getParentNode())) {
                   lCoursewareType.setParentNode(0);
                }
                // token
                String token = request.getHeader("token");
                String userId = JwtUtil.getUserId(token);
                lCoursewareType.setCreateUser(userId);
                String coursewareCode = CnToSpell.getPinYinHeadChar(lCoursewareType.getCoursewareTypeName());
                lCoursewareType.setCreateTime(new Date());
                lCoursewareType.setCoursewareTypeCode(coursewareCode);

                if (ilCoursewareTypeService.save(lCoursewareType)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除课件分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LCoursewareType lCoursewareType){
        try {
            if(lCoursewareType!=null){
                if(lCoursewareType.getCoursewareTypeId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lCoursewareType.getCoursewareTypeId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LCoursewareType> queryWrapper = new QueryWrapper<>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LCoursewareType> lCoursewareTypes = ilCoursewareTypeService.list(queryWrapper);
            for (int j = 0; j < lCoursewareTypes.size(); j++) {
                LCoursewareType lCoursewareType = lCoursewareTypes.get(j);
                ids.add(lCoursewareType.getCoursewareTypeId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LCoursewareType>();
        queryWrapper.in(true, "courseware_type_id", ids);
        ilCoursewareTypeService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新课件分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> editCoursewareType(@RequestBody LCoursewareType lCoursewareType, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lCoursewareType!=null){
            lCoursewareType.setUpdateUser(userId);
            lCoursewareType.setUpdateTime(new Date());
            if(ilCoursewareTypeService.updateById(lCoursewareType)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}

